package com.smart.car.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.smart.car.auth.config.JwtProperties;
import com.smart.car.auth.fegin.MemberClient;
import com.smart.car.auth.service.AuthService;
import com.smart.car.auth.utils.JwtUtils;
import com.smart.car.common.res.bean.ResponseResult;
import com.smart.car.member.entity.MemberUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
 * 校验用户信息
 *
 * @author zoutao
 * @date 2021/4/30
 */
@Slf4j
@Service
@EnableConfigurationProperties({JwtProperties.class})
public class AuthServiceImpl implements AuthService {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private MemberClient memberClient;

    /**
     * 通过FeignClient去访问 member-service微服务，
     * 远程调用用户服务，来验证username和password是否匹配且正确
     */
    @Override
    public String accredit(String username, String password) {
        //  1.远程调用feign接口查询用户
        ResponseResult<MemberUser> user = memberClient.queryUser(username, password);
        MemberUser userInfo = user.getData();
        // 2.判断用户是否为null,则token设为空
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }
        try {
            // 3.生成JWT
            Map<String, Object> result = new HashMap<>(16);
            result.put("id", userInfo.getId());
            result.put("username", userInfo.getPhone());
            String token = JwtUtils.generateToken(result, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            return token;
        } catch (Exception e) {
            log.error("token生成失败! ", e);
            return ("登录失败"+ "500");
        }
    }
}
